#encoding: utf-8
require 'api_session_helpers'
module GrapeAPI
  module AUTH
    class MobileSessionInterface < Grape::API
      version "auth"
      helpers GrapeAPI::APISessionHelpers
      #===登录===#
      resource :signin do
        post do
          _login = params["login"]
          _password = params["password"]
    
          if _login.nil? or _password.nil?
            unknow_user!
            return
          end
  
          _user = User.where(["lower(username) = :value OR lower(email) = :value", { :value => _login.downcase }]).first
          if _user.nil?
            unknow_user!
            return
          end
  
          if !_user.valid_password?(_password)
            wrong_password!
            return
          end
          
          if _user.active?
            _user.authentication_token = get_token
            _user.save 
            header 'AUTHTOKEN', _user.authentication_token.to_s
            header 'USERID', _user.id.to_s
            response_format!
          else
            not_active!
          end
        end
      end
      
      
      #===注册===#
      resource :signup do
        post do
          _login = params["login"]
          _passwd = params["password"]
          _body = nil
          
          _user = User.where(["lower(username) = :value OR lower(email) = :value", { :value => _login.downcase }]).first
          if _user.blank?
            begin
              _email = nil
              _username = nil
              _active_code = nil
              
              if is_email?(_login)
               _email = _login
               _username = _email
               _active_code = User.get_num_token
              else
                _username = _login
                _email = "#{_login}@openid.com"
                
                ##发送短信
                _data = {
                  :PhoneNum => _login,
                  :TrustType =>"otp_code",
                  :DeviceModel => "",
                }

                _body = http_post(SMS_PATH,_data)
                _t_body = JSON::parse(_body)
                _active_code = _t_body["code"]
              end
              _user = User.create!(:email => _email,:username => _username,:password => _passwd,:authentication_token => User.get_token,:activation_code => _active_code,:created_at=> Time.now,:updated_at => Time.now)
            rescue
            end
            
            if _user 
              header 'ACTIVATIONCODE', _user.activation_code.to_s
              response_format!
            else
              server_error!
            end
          else
            if _user.active?
                header 'ACTIVATIONCODE', _user.activation_code.to_s
                already_have!
            else
              if is_email?(_login)
                 _user.send_web_active_mail
                header 'ACTIVATIONCODE', _user.activation_code.to_s
              else
                _data = {
                  :PhoneNum => _login,
                  :TrustType =>"otp_code",
                  :DeviceModel => "",
                }
                _body = http_post(SMS_PATH,_data)
                _t_body = JSON::parse(_body)
                _active_code = _t_body["code"]
                _user.activation_code = _active_code
                if _user.save
                  header 'ACTIVATIONCODE', _user.activation_code.to_s
                else
                  server_error!
                end
              end
              response_format!
            end
          end
        end
      end
      
      #=====激活用户=====#
      resource :active_user do
        post do
          _login = params["login"]
          _active_code = params["active_code"]
          _user = User.where(["lower(username) = :value OR lower(email) = :value", { :value => _login.downcase }]).first
          if _user
            if _user.active?
              already_actived!
            else
              if _user.activation_code.to_s == _active_code
                _user.send(:activate!)
                response_format!
              else
                unknown_activecode!
              end
            end
          else
            unknow_user!
          end
        end
      end
      
      #====忘记密码=====#
      resource :forget_passwd do
        #======应该用get
        post do
          _login = params["login"]
          _device = params["DeviceModel"]
          _user = nil
          _body = nil
          _reset_token = nil
          _auth_token = nil

          if is_email?(_login)
            _user = User.find_by_email(_login.downcase)
            if _user
              if _user.activation_code.blank?
                begin
                  _reset_token = User.get_num_token
                  _user.reset_password_token = _reset_token
                  _user.save
                  UserMailer.forget_password_email(_user).deliver
                rescue
                end
              else
                not_active!
              end
            else
              unknow_user!
            end
          else
            _user = User.find_by_username(_login)
            if _user 
              if _user.activation_code.blank?
                _data = {
                  :PhoneNum => _login,
                  :TrustType =>"otp_code",
                  :DeviceModel => _device,
                }
                _body = http_post(SMS_PATH,_data)
                _t_body = JSON::parse(_body)
                _reset_token = _t_body["code"]
                _user.reset_password_token = _reset_token
                _user.save
              else
                not_active!
              end
             else
               unknow_user!
             end
          end
          
          header 'RESETTOKEN', _user.reset_password_token.to_s
          response_format! 
        end
      end
      
      #====== 重置密码 =====#
      resource :reset_passwd do
        put do
          _token = params["reset_token"]
          _login = params["login"]
          _new_pwd = params["npwd"]
          _body = {}
          #检查密码
          if _new_pwd.size < 6 
            shortpwd_error!
          end
          #检查用户
          _user = User.where(["lower(username) = :value OR lower(email) = :value", { :value => _login.downcase }]).first
          if _user
            #检查验证码
            if _user.reset_password_token.to_s == _token
              _user.password = _new_pwd
              if _user.save
                response_format!
              end
            else
              token_expired!
            end
          else
            unknow_user!
          end
        end
      end
      
      #===退出===#
      resource :signout do
        before do
          authenticate!
        end
        post do
          _user_id = params["user_id"]
          if current_user.id.to_s == _user_id
            current_user.authentication_token = get_token
            current_user.save
            env["HTTP_ACCESSTOKEN"] = nil
            current_user = nil
            response_format!
          else
            unknow_user!
          end
        end
      end
      #=====end=====#
      
      #====查询====#
       #查找用户
      resource :find_user do
        get "/:login" do
          _login = params["login"]
          u = User.where(["lower(username) = :value OR lower(email) = :value", { :value => _login.downcase }]).first
          if u
            response_format!
          else
            unknow_user!
          end
        end
      end
    end
  end
end